<template>
  <div>
  <page-header-wrapper content="角色与权限用于管理各角色对各页面的可见权限">
  </page-header-wrapper>
  <div style="height: 30px"></div>
  <a-card>
    <a-table
      :columns="columns"
      :dataSource="data"
      :rowKey="record=>record.id"
    >
      <a slot="roleName" slot-scope="text">{{ text }}</a>
      <span slot="customTitle"><a-icon type="smile-o" />角色名</span>
      <span slot="permissions" slot-scope="permissions">
      <a-tag
        :closable="visible"
        @close="e => deletePermissions(e,tag)"
        v-for="tag in permissions"
        :key="tag.permissionName"
        :color="getColor()"
      >
        {{ tag.permissionName.toUpperCase() }}
      </a-tag>
    </span>
      <span slot="action" slot-scope="text, record">
      <a @click="editStatus(record)">{{editButtonName}}</a>
      <a-divider type="vertical" />
      <a @click="addTagModalShowOrHide(record.permissions,record)">添加</a>
    </span>
    </a-table>
  </a-card>
  <a-modal
    title="添加权限"
    :visible="addTagModalStatus"
    :confirm-loading="addTagModalConfirmLoading"
    @ok="addTagModalHandelOK"
    @cancel="addTagModalHandelCancel"
  >
    <template>
      <a-checkable-tag
        v-for="per in tempPermission"
        :key="per.id"
        v-model="per.show"
        @change="checked=>checkableTagStatusHandelChange(checked,per.id,per)"
      >
        {{per.permissionName}}
      </a-checkable-tag>
    </template>
  </a-modal>
<!--    <pCRUDTable title="ces" :columns="c1" :data-source="d1" :delete-data="()=>{}"></pCRUDTable>-->
<!--    <p-file-upload button-name="不允许txt" :format-filtering="[{name:'txt',isUpload:false},{name:'sql',isUpload: true}]"></p-file-upload>-->
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import pFileUpload from '@/assembly/File/pFileUpload'
export default {
  name: 'roleAndPermissions',
  components: {
    PageHeaderWrapper,
    pFileUpload
  },
  data () {
    return {
      tempPermission: [],
      checkableTagStatus: false,
      permission: [],
      addTagModalConfirmLoading: false,
      addTagModalStatus: false,
      visible: false,
      editButtonName: '编辑',
      tempRoleIdAndPermissionsData: [],
      columns: [
        {
          dataIndex: 'roleName',
          key: 'roleName',
          slots: { title: 'customTitle' },
          scopedSlots: { customRender: 'roleName' }
        },
        {
          title: '权限页',
          dataIndex: 'permissions',
          key: 'permissions',
          scopedSlots: { customRender: 'permissions' }
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      data: [],
      c1: [
        {
          dataIndex: 'name',
          key: 'name',
          slots: { title: 'customTitle' },
          scopedSlots: { customRender: 'name' }
        },
        {
          title: 'Age',
          dataIndex: 'age',
          key: 'age'
        },
        {
          title: 'Address',
          dataIndex: 'address',
          key: 'address'
        },
        {
          title: 'Tags',
          key: 'tags',
          dataIndex: 'tags',
          scopedSlots: { customRender: 'tags' }
        },
        {
          title: 'Action',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      d1: [
        {
          key: '1',
          name: 'John Brown',
          age: 32,
          address: 'New York No. 1 Lake Park',
          tags: ['nice', 'developer']
        },
        {
          key: '2',
          name: 'Jim Green',
          age: 42,
          address: 'London No. 1 Lake Park',
          tags: ['loser']
        },
        {
          key: '3',
          name: 'Joe Black',
          age: 32,
          address: 'Sidney No. 1 Lake Park',
          tags: ['cool', 'teacher']
        }
      ]
    }
  },
  methods: {
    ...mapActions(['GetRoleAndPermission', 'GetDistinctPermissions', 'DeleteByRoleIdAndPermissionsId', 'AddRoleAssociatedPermissions']),
    show () {
      const {
        GetRoleAndPermission
      } = this
      GetRoleAndPermission().then((res) => {
        if (res.code === '200') {
          this.data = JSON.parse(JSON.stringify(res.result))
        } else {
          this.$message.error(res.message)
        }
      })
    },
    checkableTagStatusHandelChange (checked, perId, per) {
      console.log(per)
      const find = this.tempRoleIdAndPermissionsData.find(item => item.id === perId)
      if (find === undefined) {
        this.tempRoleIdAndPermissionsData.push(per)
      } else {
        find.show = checked
      }
      console.log(this.tempRoleIdAndPermissionsData)
    },
    showSelect () {
      this.addTagShowStatus = false
    },
    getPermissionAll () {
      const {
        GetDistinctPermissions
      } = this
      GetDistinctPermissions().then((res) => {
        if (res.code === '200') {
          for (let i = 0; i < res.result.length; i++) {
            this.$set(res.result[i], 'tagShow', false)
          }
          // console.log(res.result)
          this.permission = JSON.parse(JSON.stringify(res.result))
          console.log(this.permission)
        }
      })
    },
    editStatus (record) {
      console.log(record)
      if (this.visible === false) {
        this.editButtonName = '取消'
        this.visible = true
      } else {
        this.editButtonName = '编辑'
        this.visible = false
      }
    },
    addTagModalShowOrHide (record, records) {
      console.log(records)
      console.log(record)
      console.log(this.tempRoleIdAndPermissionsData)
      // eslint-disable-next-line no-unused-vars
      const roleId = records.id
      const perList = []
      if (record !== undefined && record.length !== 0) {
        this.tempPermission = JSON.parse(JSON.stringify(record))
        for (let i = 0; i < this.permission.length; i++) {
          const temp = this.tempPermission.find(item => item.id === this.permission[i].id)
          if (temp !== undefined) {
            this.$set(temp, 'show', true)
            perList.push(temp)
          } else {
            const temp = this.permission[i]
            this.$set(temp, 'show', false)
            perList.push(temp)
          }
        }
      } else {
        for (let i = 0; i < this.permission.length; i++) {
          const permissionElement = this.permission[i]
          this.$set(permissionElement, 'show', false)
          perList.push(permissionElement)
        }
      }
      this.tempRoleIdAndPermissionsData = perList
      for (let i = 0; i < this.tempRoleIdAndPermissionsData.length; i++) {
          console.log(roleId)
          this.$set(this.tempRoleIdAndPermissionsData[i], 'roleId', roleId)
      }
      this.tempPermission = JSON.parse(JSON.stringify(perList))
      // 添加按钮的状态
      this.addTagModalStatus = !this.addTagModalStatus
    },
    addTagModalHandelOK () {
      const errorData = []
      const {
        AddRoleAssociatedPermissions,
        DeleteByRoleIdAndPermissionsId
      } = this
      for (let i = 0; i < this.tempRoleIdAndPermissionsData.length; i++) {
        if (this.tempRoleIdAndPermissionsData[i].show === true) {
          // 插入
          AddRoleAssociatedPermissions(this.tempRoleIdAndPermissionsData[i]).then(res => {
            if (res.code === '200') {
              // 获取所有角色
              this.show()
              // 获取所有权限列表
              this.getPermissionAll()
            } else {
              errorData.push(this.tempRoleIdAndPermissionsData[i])
              console.log('失败')
            }
          })
        } else {
          // 删除
          DeleteByRoleIdAndPermissionsId(this.tempRoleIdAndPermissionsData[i]).then(res => {
            if (res.code === '200') {
              // 获取所有角色
              this.show()
              // 获取所有权限列表
              this.getPermissionAll()
            } else {
              errorData.push(this.tempRoleIdAndPermissionsData[i])
              console.log('失败')
            }
          })
        }
      }
      this.addTagModalStatus = !this.addTagModalStatus
    },
    addTagModalHandelCancel () {
      this.addTagModalStatus = !this.addTagModalStatus
    },
    getColor () {
      // 可均衡获取 0 到 9 的随机整数。
      const num = Math.floor(Math.random() * 10)
      if (num === 0) {
        return 'pink'
      }
      if (num === 1) {
        return 'red'
      }
      if (num === 2) {
        return 'orange'
      }
      if (num === 3) {
        return 'green'
      }
      if (num === 4) {
        return 'cyan'
      }
      if (num === 5) {
        return 'blue'
      }
      if (num === 6) {
        return 'purple'
      }
      if (num === 7) {
        return '#f50'
      }
      if (num === 8) {
        return '#2db7f5'
      }
      if (num === 9) {
        return '#87d068'
      }
      return '#108ee9'
    },
    deletePermissions (e, tag) {
      console.log(e)
      console.log(tag)
      const {
        DeleteByRoleIdAndPermissionsId
      } = this
      DeleteByRoleIdAndPermissionsId(tag).then(res => {
        if (res.code === '200') {
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  },
  created () {
    // 获取所有角色
    this.show()
    // 获取所有权限列表
    this.getPermissionAll()
  }
}
</script>

<style scoped>
</style>
